"""
File: utils.py
Author: ershixiong
Date: 2023/12/21
describe:

"""
import datetime
import glob
import os

import allure
import yaml
from selenium.webdriver.chrome.webdriver import WebDriver


def get_root_dir():
    """
    获取根目录所在路径
    :return:
    """
    root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    return root_dir


def get_timestamp():
    """
    获取时间戳
    :return:
    """
    timestamp = int(datetime.datetime.now().timestamp())
    return timestamp


def save_screen(driver: WebDriver):
    """
    截图
    :param driver:
    :return:
    """
    timestamp = get_timestamp()
    screenshot_path = os.sep.join([get_root_dir(), f'screen_shot_pic/screen_shot_{timestamp}.PNG'])
    driver.save_screenshot(screenshot_path)
    allure.attach.file(source=screenshot_path, name='点击截图', attachment_type=allure.attachment_type.PNG)


def ele_add_border(driver: WebDriver, ele):
    """
    给定位到的元素添加红色边框
    :param driver:
    :param ele:定位到的元素
    :return:
    """
    driver.execute_script('arguments[0].style.border="2px solid red";', ele)


def delete_folder_files(folder_path, threshold=50, num_to_keep=10):
    """
    删除 单个文件夹下过多的文件
    :param folder_path:目标文件夹
    :param threshold:文件最大数量
    :param num_to_keep:保留文件数量
    :return:
    """
    # 获取文件夹下所有文件的列表
    folder_path = os.sep.join([get_root_dir(), folder_path])
    all_files = glob.glob(os.path.join(folder_path, '*'))

    # 如果文件数量超过阈值
    if len(all_files) > threshold:
        # 计算要删除的文件数量
        num_to_delete = len(all_files) - num_to_keep

        # 获取要删除的文件列表（前 num_to_delete 个），按修改时间升序排序
        files_to_delete = sorted(all_files, key=os.path.getmtime)[:num_to_delete]

        # 删除文件
        for file_to_delete in files_to_delete:
            try:
                os.remove(file_to_delete)
                print(f"Deleted: {file_to_delete}")
            except Exception as e:
                print(f"Error deleting {file_to_delete}: {e}")


def delete_folders_files(paths, threshold=50, num_to_keep=10):
    """
    删除 多个文件夹 下过多的文件
    :param paths:[path1,path2,path3]
    :param threshold:
    :param num_to_keep:
    :return:
    """
    for path in paths:
        delete_folder_files(path, threshold, num_to_keep)


def get_yaml(path):
    """
    根据路径，获取yaml文件数据
    :param path:
    :return:
    """
    path = os.sep.join([get_root_dir(), path])
    with open(path, 'r', encoding='utf-8') as f:
        return yaml.safe_load(f)
